package org.arch_learn.orm_starter.sqlSession;

import org.arch_learn.flashboot.context.GlobalContext;
import org.arch_learn.orm_starter.annos.Mapper;
import org.arch_learn.orm_starter.config.XmlMapperBuilder;
import org.arch_learn.orm_starter.io.Resources;
import org.arch_learn.orm_starter.po.Configuration;
import org.arch_learn.orm_starter.utils.ScanUtils;
import org.dom4j.DocumentException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private Configuration configuration;
    private String mappersLocation;

    public DefaultSqlSessionFactory(Configuration configuration, String mappersLocation) {
        this.configuration = configuration;
        this.mappersLocation = mappersLocation;
    }

    @Override
    public SqlSession openSession() {
        return new DefaultSqlSession(configuration);
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public String getMappersLocation() {
        return mappersLocation;
    }

    public void setMappersLocation(String mappersLocation) {
        this.mappersLocation = mappersLocation;
    }

    //扫描解析mapper.xml，以及为mapper.class生成代理对象
    public void afterProperties() throws IOException, DocumentException {
        Set<String> xmlPaths = ScanUtils.getXmlPaths(mappersLocation);
        for (String xmlpath : xmlPaths) {
            InputStream resourceAsStream = Resources.getResourceAsStream(xmlpath);
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        Set<String> mapperClasses = ScanUtils.getMapperNames(mappersLocation);

        mapperClasses.forEach(v -> {
            try {
                Class<?> clazz = Class.forName(v);
                Mapper annotation = clazz.getAnnotation(Mapper.class);
                String value = annotation.value();
                SqlSession sqlSession = this.openSession();
                Object sqlSessionMapper = sqlSession.getMapper(clazz);
                GlobalContext.globalSingletonPool.put(value.length() == 0 ? clazz.getName() : value, sqlSessionMapper);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        });
    }
}
